package com.qt.myboot.handler;

import com.qt.myboot.common.Result;
import com.qt.myboot.enums.ResultEnum;
import com.qt.myboot.exception.UserErrorCodeException;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.UnauthorizedException;
import org.hibernate.StaleObjectStateException;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;


@ControllerAdvice
public class BootExceptionHandler {

    @ExceptionHandler(value = DataIntegrityViolationException.class)
    @ResponseBody
    public Result sqlExceptionHandler(DataIntegrityViolationException e) throws Exception{
        return new Result(ResultEnum.USER_ADD_DUPLICATION, false);
        //return new Result(ResultEnum.UNDEFINED_ERROR, false, e.getMessage());
    }

    @ExceptionHandler(value = UserErrorCodeException.class)
    @ResponseBody
    public Result userErrorException(UserErrorCodeException e) throws Exception{
        return Result.failed(e.getErrorEnum().getDesc());
    }

    /**
     * 无权限 访问处理
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = AuthorizationException.class)
    public Result defaultExceptionHandler(AuthorizationException e) throws Exception {
        return new Result(ResultEnum.USER_NO_PERMISSION, false);
    }

    /**
     * 数据库发生锁异常处理 乐观锁
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = StaleObjectStateException.class)
    public Result staleObjectStateExceptionHandler(StaleObjectStateException e) throws Exception {
        return new Result(ResultEnum.SQL_OPTIMISTIC_ERROR, false);
    }
}
